package com.ls.utils.pay;

//import com.luo.expression.bean.entity.wechat.OrderWechatPrepare;

import java.io.StringReader;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

public class XmlUtils {

    /**
     * 将String类型的xml转换成对象
     *
     * @param clazz
     * @param xmlStr
     * @return
     */
    public static Object convertXmlStrToObject(String xmlStr, Class clazz) {
        Object xmlObject = null;
        try {
            JAXBContext context = JAXBContext.newInstance(clazz);
            // 进行将Xml转成对象的核心接口
            Unmarshaller unmarshaller = context.createUnmarshaller();
            StringReader sr = new StringReader(xmlStr);
            xmlObject = unmarshaller.unmarshal(sr);
        } catch (JAXBException e) {
            e.printStackTrace();
        }
        return xmlObject;
    }


    public static void main(String[] args) {
        String xml = "<xml>\n" +
                "    <return_code>\n" +
                "        <![CDATA[SUCCESS]]>\n" +
                "    </return_code>\n" +
                "    <return_msg>\n" +
                "        <![CDATA[OK]]>\n" +
                "    </return_msg>\n" +
                "    <appid>\n" +
                "        <![CDATA[wx40807d7054adcb38]]>\n" +
                "    </appid>\n" +
                "    <mch_id>\n" +
                "        <![CDATA[1598140651]]>\n" +
                "    </mch_id>\n" +
                "    <device_info>\n" +
                "        <![CDATA[xiaochengxu]]>\n" +
                "    </device_info>\n" +
                "    <nonce_str>\n" +
                "        <![CDATA[1ldmmNMgJwwjwvDu]]>\n" +
                "    </nonce_str>\n" +
                "    <sign>\n" +
                "        <![CDATA[BB383CC542BA7C7FBBF30C9D78CACA52]]>\n" +
                "    </sign>\n" +
                "    <result_code>\n" +
                "        <![CDATA[SUCCESS]]>\n" +
                "    </result_code>\n" +
                "    <prepay_id>\n" +
                "        <![CDATA[wx191439309814689f9e87c7141706066200]]>\n" +
                "    </prepay_id>\n" +
                "    <trade_type>\n" +
                "        <![CDATA[JSAPI]]>\n" +
                "    </trade_type>\n" +
                "</xml>";
        xml = xml.replace("<![CDATA[", "").replace("]]>", "");
        WechatPrepareReturn orderWechatPrepare = (WechatPrepareReturn) XmlUtils.convertXmlStrToObject(xml, OrderWechatPrepare.class);
        System.out.println(orderWechatPrepare);
    }

}
